package com.bonana.backend.filter;

import com.bonana.utils.ConvertUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;


public class BackendFilter implements Filter {

    protected FilterConfig filterConfig = null;
    private static Logger logger = LogManager.getLogger(BackendFilter.class);

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest hsrequest = (HttpServletRequest) request;
        HttpSession session = hsrequest.getSession();

        boolean flg = false;
        String noFilterUrlParams = this.filterConfig.getInitParameter("noFilterUrlParams");
        String[] noFilterUrls = noFilterUrlParams.split(";");
        for (String url : noFilterUrls) {
            String tmpUrl = hsrequest.getContextPath() + url;


            if (tmpUrl.equalsIgnoreCase(hsrequest.getRequestURI()) || hsrequest.getRequestURI().indexOf(tmpUrl) != -1 || hsrequest.getRequestURI().indexOf(url) != -1) {
                flg = true;
                break;
            }
        }

        if ((session.getAttribute("session.uid") != null && ConvertUtils.toInteger(session.getAttribute("session.uid")) > 0) || flg) {
            chain.doFilter(request, response);
        } else {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print("<script>");
            out.print("if(parent != null) {");
            out.print("     parent.location.href='" + hsrequest.getContextPath() + "/login" + "'; ");
            out.print("} else { ");
            out.print("     document.location.href='" + hsrequest.getContextPath() + "/login" + "'; ");
            out.print("} ");
            out.print("</script>");
            out.close();
            return;
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

}
